/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { useRouter } from 'vue-router'
import type { Router } from 'vue-router'
import { h, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { NButton, useDialog } from 'naive-ui'
import {
  getInstanceListPaging,
  releaseInstance
} from '@/service/modules/instance'
import { Instance } from '@/service/modules/instance/types'
import { instanceStatusType, computeResourceSizeType } from '@/common/common'

export function useTable() {
  const router: Router = useRouter()
  const { t } = useI18n()
  const dialog = useDialog()

  const variables = reactive({
    columns: [],
    tableWidth: 500,
    tableData: [] as Instance[],
    page: ref(1),
    pageSize: ref(10),
    searchVal: ref(''),
    totalPage: ref(1),
    totalElements: ref(0),
    showModalRef: ref(false),
    statusRef: ref(0),
    row: {},
    loadingRef: ref(false)
  })

  const onHandleManage = (row: any) => {
    router.push(`/instance/details/${row.instanceId}`)
  }

  const onHandleDelete = (row: any) => {
    const d = dialog.warning({
      title: `${t('instance.delete_tips')}${row.instance}`,
      content: `${t('instance.delete_tips_desc')}`,
      positiveText: t('common.negativeText'),
      negativeText: t('instance.release'),
      onNegativeClick: () => {
        d.loading = true
        return new Promise((resolve) => {
          releaseInstance(row.instanceId).then(() => {
            resolve(true)
            getList()
          })
        })
      }
    })
  }

  const getList = async () => {
    if (variables.loadingRef) return
    variables.loadingRef = true

    const listRes = await getInstanceListPaging({
      pageNum: variables.page,
      pageSize: variables.pageSize,
      searchVal: variables.searchVal,
      engineType: ''
    })
    variables.loadingRef = false
    variables.tableData = listRes.totalList
    variables.totalPage = listRes.totalPage
    variables.totalElements = listRes.total
  }

  const changePage = (page: number) => {
    variables.page = page
    getList()
  }

  const changePageSize = (pageSize: number) => {
    variables.page = 1
    variables.pageSize = pageSize
    getList()
  }

  const createColumns = (variables: any) => {
    const instanceStatusTypeConfig = instanceStatusType(t)
    const computeResourceSizeTypeConfig = computeResourceSizeType(t)
    variables.columns = [
      {
        title: t('instance.instance_name'),
        key: 'instance',
        render(row: any) {
          return h(
            NButton,
            {
              text: true,
              type: 'info',
              strong: true,
              size: 'small',
              onClick: () => {
                onHandleManage(row)
              }
            },
            { default: () => row.instance }
          )
        }
      },
      {
        title: t('instance.engine_type'),
        key: 'engineType'
      },
      {
        title: t('instance.compute_resource_size'),
        key: 'computeResourceSize',
        render(row: any) {
          return h(
            'span',
            computeResourceSizeTypeConfig[
              row.computeResourceSize as keyof typeof computeResourceSizeTypeConfig
            ].desc
          )
        }
      },
      {
        title: t('instance.status'),
        key: 'status',
        render(row: any) {
          return h(
            'span',
            {
              style: {
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'start',
                alignItems: 'center'
              }
            },
            [
              h('img', {
                src: `${
                  instanceStatusTypeConfig[
                    row.status as keyof typeof instanceStatusTypeConfig
                  ].icon
                }`,
                style: {
                  width: '16px',
                  height: '16px',
                  marginRight: '5px'
                }
              }),
              h(
                'span',
                instanceStatusTypeConfig[
                  row.status as keyof typeof instanceStatusTypeConfig
                ].desc
              )
            ]
          )
        }
      },
      {
        title: t('instance.duration'),
        key: 'taskRunningTime'
      },
      {
        title: t('instance.create_user'),
        key: 'createdBy'
      },
      {
        title: t('instance.create_time'),
        key: 'createTime'
      },
      {
        title: t('common.action'),
        key: 'actions',
        render(row: any) {
          return h('span', null, [
            h(
              NButton,
              {
                text: true,
                type: 'info',
                strong: true,
                size: 'small',
                onClick: () => {
                  onHandleManage(row)
                }
              },
              { default: () => t('instance.manage') }
            ),
            h(
              NButton,
              {
                text: true,
                type: 'info',
                strong: true,
                size: 'small',
                style: {
                  'margin-left': '10px'
                },
                onClick: () => {
                  onHandleDelete(row)
                }
              },
              { default: () => t('common.delete') }
            )
          ])
        }
      }
    ]
  }

  return {
    variables,
    createColumns,
    getList,
    changePage,
    changePageSize
  }
}
